//
//  WJ_TJ_ViewController.m
//  WJBSApp
//
//  Created by dllo on 16/7/14.
//  Copyright © 2016年 王景伟. All rights reserved.
//

#import "WJ_TJ_ViewController.h"
#import "WJ_Search_ViewController.h"
#import "WJTjTableViewCell.h"
#import "WJLeftModel.h"
#import "WJRightCell.h"
#import "WJRightModel.h"
#import "SVProgressHUD.h"
#import "WJLastViewController.h"

// 陷入了一个死胡同 怎么办? 1.让左面的数据实体化  2.就是怎么让第一个数据线先刷出来

#define LeftSelectedRow self.leftArray[self.leftTableView.indexPathForSelectedRow.row]

@interface WJ_TJ_ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,retain) WJBaseTableView *leftTableView;

@property (nonatomic,retain) WJBaseTableView *rightTableView;

@property (nonatomic,retain) NSMutableArray *leftArray;

@property (nonatomic,strong) NSMutableArray *rightArray;

// 记录Lable的tag值
@property (nonatomic,assign) NSInteger presentTag;
/**
 *  请求参数 ??
 */
@property (nonatomic, strong) NSMutableDictionary *params;

@property (nonatomic, assign) NSInteger selectRow;

@end

@implementation WJ_TJ_ViewController

static NSString *const LeftCell = @"leftCell";
static NSString *const RightCell = @"rightCell";

-(void)dealloc
{
    [_leftTableView release];
    [_rightTableView release];
    [_leftArray release];
    [_rightArray release];
    [_params release];
    self.leftTableView.delegate = nil;
    self.leftTableView.dataSource = nil;
    self.rightTableView.delegate = nil;
    self.rightTableView.dataSource = nil;
    [super dealloc];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.presentTag = 1000;
    
    self.selectRow = 0;
    
    self.leftArray = [NSMutableArray array];
    
    self.rightArray = [NSMutableArray array];
    
    [self createConfig];
    
    // 添加左侧数据
    [self createData];
    
    [self createView];
    
    //显示指示器
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
    [SVProgressHUD show];
    
    // 右侧数据刷新
    [self setupRefresh];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}



- (void)createConfig
{
    self.title = @"推荐关注";
    
    // 影藏系统的返回按钮
    self.navigationItem.hidesBackButton = YES;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationButtonReturn@3x副本.png" hightImage:@"navigationButtonReturnClick@3x副本.png" target:self action:@selector(tjLeftAction)];
    
    // 右面的搜索按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"nav_search_icon~iphone.png" hightImage:@"nav_search_icon_click~iphone.png" target:self action:@selector(tjRightAction)];
    
}

// 左面返回上一页
- (void)tjLeftAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 右面键入 搜索界面
- (void)tjRightAction
{
    WJ_Search_ViewController *searchVC = [[WJ_Search_ViewController alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}

- (void)createView
{
    // 左面的TabView
    
    self.leftTableView = [[WJBaseTableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH / 7, HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.leftTableView];
    self.leftTableView.bounces = NO;
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.leftTableView.rowHeight = 50;
    [self.leftTableView registerClass:[WJTjTableViewCell class] forCellReuseIdentifier:LeftCell];
    [_leftTableView release];
    
    // 右面的TabView
    
    self.rightTableView = [[WJBaseTableView alloc]initWithFrame:CGRectMake(WIDTH / 7, 0, WIDTH * 6 / 7, HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.rightTableView];
    self.rightTableView.delegate = self;
    self.rightTableView.dataSource = self;
    self.rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.rightTableView.rowHeight = HEIGHT / 9;
    [self.rightTableView registerClass:[WJRightCell class] forCellReuseIdentifier:RightCell];
    [_rightTableView release];
    
}

// = 右面是set  左面是get
- (void)createData
{
    NSString *str = [KESHAN stringByAppendingPathComponent:@"左面.plist"];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"category";
    params[@"c"] = @"subscribe";
    
    // 左面的数据
    [WJNetTool GET:@"http://api.budejie.com/api/api_open.php" body:params header:nil response:WJJSON success:^(id resuposeObject) {
        
        NSDictionary *dic = resuposeObject;
        
        // 写入文件
        BOOL result = [dic writeToFile:str atomically:YES];
        if (result) {
            NSLog(@"分类页写入数据成功");
        }
        else {
            NSLog(@"分类页写入数据失败");
        }
        
#pragma mark - 需要加以保护 以防没有数据
        if (dic == nil) return;
        
        NSArray *array = dic[@"list"];
        
        for (NSDictionary *dic in array) {
            WJLeftModel *model = [[WJLeftModel alloc]initWithDic:dic];
            [self.leftArray addObject:model];
            [model release];
        }
        // 刷新数据
        [self.leftTableView reloadData];
        // 隐藏指示器
        [SVProgressHUD dismiss];
        // 默认选中第一行
        //                [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        // 让右侧进入刷新状态
        [self.rightTableView.mj_header beginRefreshing];
        
    } failure:^(NSError *error) {
        //显示加载失败的信息
        [SVProgressHUD showErrorWithStatus:@"加载失败"];
        [SVProgressHUD dismiss];
        
        // 列表大字典
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:str];
        if (dic == nil) return;
        
        NSArray *array = dic[@"list"];
        
        for (NSDictionary *dic in array) {
            WJLeftModel *model = [[WJLeftModel alloc]initWithDic:dic];
            [self.leftArray addObject:model];
            [model release];
        }
        // 刷新数据
        [self.leftTableView reloadData];
        // 隐藏指示器
        [SVProgressHUD dismiss];
        // 让右侧进入刷新状态
        [self.rightTableView.mj_header beginRefreshing];
        
    }];
    
    
    
}


#pragma mark 添加刷新控件
-(void)setupRefresh {
    //顶部
    self.rightTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];
    
    //底部
    self.rightTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];
}

#pragma mark 加载用户数据
-(void)loadNewUsers {
    
    
    if (self.leftArray.count == 0) {
        [self.rightTableView.mj_header endRefreshing];
        [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
        return;
    }
    
    WJLeftModel *leftModel = self.leftArray[self.selectRow];
    
    //设置当前页码为1
    leftModel.currentPage = 1;
    //设置参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] = leftModel.ID;
    params[@"page"] = @(leftModel.currentPage);
    self.params = params;
    // 发送请求给服务器,加载右侧数据
    NSString *str = [KESHAN stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist",leftModel.ID]];
    [WJNetTool GET:@"http://api.budejie.com/api/api_open.php" body:params header:nil response:WJJSON success:^(id resuposeObject) {
        
        NSDictionary *dic = resuposeObject;
        
        // 写入文件
        BOOL result = [dic writeToFile:str atomically:YES];
        if (result) {
            NSLog(@"分类页写入数据成功");
        }
        else {
            NSLog(@"分类页写入数据失败");
        }
        
        NSArray *array = dic[@"list"];
        
        leftModel.total = dic[@"total"];
        
        [self.rightArray removeAllObjects];
        
        // 左侧的数据里面添加了右侧的数据
        for (NSDictionary *dic in array) {
            
            WJRightModel *model = [[WJRightModel alloc]initWithDic:dic];
            
            [self.rightArray addObject:model];
            
            [model release];
        }
        
        //不是最后一次请求
        if (self.params != params) return;
        //刷新表格
        [self.rightTableView reloadData];
        //结束刷新
        [self.rightTableView.mj_header endRefreshing];
        //让底部控件结束刷新
        [self checkFooterState];
        
    } failure:^(NSError *error) {
        if (self.params != params) return;
        //提醒
        [SVProgressHUD showErrorWithStatus:@"加载失败"];
        
        // 列表大字典
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:str];
        NSArray *array = dic[@"list"];
        
        leftModel.total = dic[@"total"];
        
        [self.rightArray removeAllObjects];
        
        // 左侧的数据里面添加了右侧的数据
        for (NSDictionary *dic in array) {
            
            WJRightModel *model = [[WJRightModel alloc]initWithDic:dic];
            
            [self.rightArray addObject:model];
            
            [model release];
        }
        
        //不是最后一次请求
        if (self.params != params) return;
        //刷新表格
        [self.rightTableView reloadData];
        //结束刷新
        [self.rightTableView.mj_header endRefreshing];
        //让底部控件结束刷新
        [self checkFooterState];

        
    }];
}
#pragma mark 加载更多用户数据
-(void)loadMoreUsers {
    
    if (self.leftArray.count == 0) {
        [self.rightTableView.mj_header endRefreshing];
        [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
        return;
    }
    
    WJLeftModel *leftModel = self.leftArray[self.selectRow];
    //设置参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] = leftModel.ID;
    params[@"page"] = @(++leftModel.currentPage);
    self.params = params;
    
    [WJNetTool GET:@"http://api.budejie.com/api/api_open.php" body:params header:nil response:WJJSON success:^(id resuposeObject) {
        
        NSDictionary *dic = resuposeObject;
        
        NSArray *array = dic[@"list"];
        
        leftModel.total = dic[@"total"];
        
        // 左侧的数据里面添加了右侧的数据
        for (NSDictionary *dic in array) {
            
            WJRightModel *model = [[WJRightModel alloc]initWithDic:dic];
            
            [self.rightArray addObject:model];
            
            [model release];
        }
        
        //不是最后一次请求
        if (self.params != params) return;
        //刷新表格
        [self.rightTableView reloadData];
        //让底部控件结束刷新
        [self checkFooterState];
        
    } failure:^(NSError *error) {
        if (self.params != params) return;
        //提醒
        [SVProgressHUD showErrorWithStatus:@"加载失败"];
        //结束刷新
        [self.rightTableView.mj_footer endRefreshing];
    }];
}



#pragma mark - UItableView dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.leftTableView]) {
        return self.leftArray.count;
    }
    
    return self.rightArray.count;
}

#pragma mark 检查底部是否全部加载完毕
-(void)checkFooterState {
    
    WJLeftModel *leftModel = self.leftArray[self.selectRow];
    
    NSInteger count = self.rightArray.count;
    //每次刷新右边数据时，都控制footer显示或隐藏
    self.rightTableView.mj_footer.hidden = (count == 0);
    if (count == [leftModel.total integerValue]) { //全部加载完成
        [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
    } else { //还没有加载完毕
        [self.rightTableView.mj_footer endRefreshing];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.leftTableView]) {
        
        WJTjTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LeftCell];
        WJLeftModel *leftModel = self.leftArray[indexPath.row];
        
        cell.nameLable.text = leftModel.name;
        
        cell.redLable.tag = 1000 + indexPath.row;
        if (self.presentTag == indexPath.row + 1000) {
            cell.redLable.hidden = NO;
        }
        
        // 将选择的设置为无否则不变色
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    if ([tableView isEqual:self.rightTableView]) {
        
        WJRightCell *cell = [tableView dequeueReusableCellWithIdentifier:RightCell];
        
        WJRightModel *rightModel = self.rightArray[indexPath.row];
        
        cell.model = rightModel;
        
        return cell;
    }
    return nil;
}
#pragma mark - UITableView delegate  点击进入关注
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.leftTableView]) {
        
        WJTjTableViewCell *cell = (WJTjTableViewCell *)[self.leftTableView cellForRowAtIndexPath:indexPath];
        
        // 将上次点击的隐藏
        UILabel *lable = [self.leftTableView viewWithTag:self.presentTag];
        lable.hidden = YES;
        
        // 将本次的变色
        cell.redLable.hidden = NO;
        self.presentTag = indexPath.row + 1000;
        //结束刷新
        [self.rightTableView.mj_header endRefreshing];
        [self.rightTableView.mj_footer endRefreshing];
        
        //刷新表格，马上显示当前category的用户数据，不要让用户看到上一个数据
        [self.rightTableView reloadData];
        //发送请求给服务器
        //进入下拉刷新状态
        [self.rightTableView.mj_header beginRefreshing];
        
        self.selectRow = indexPath.row;
        
    }
    
    if ([tableView isEqual:self.rightTableView]) {
        
        WJLastViewController *vc = [[WJLastViewController alloc]init];
        
        WJRightModel *model = self.rightArray[indexPath.row];
        
        vc.userID = [NSString stringWithFormat:@"%ld",(long)model.uid];
        
        vc.userName = model.screen_name;
        
        [self.navigationController pushViewController:vc animated:YES];
        
        [vc release];
    }
    
}

//#pragma mark - 加入数据库的地方啊啊啊啊啊啊啊啊阿啊啊啊啊啊啊啊啊阿啊啊啊啊啊
//- (void)gzAction:(WJBaseButton *)button
//{
//    NSLog(@"%ld",button.tag);
//    WJRightModel *model = self.rightArray[button.tag - 1000];
//    NSLog(@"%@",model.screen_name); // 将这个存入数据库  model.UID 和ScroNmae;
//}












//#pragma mark - 下拉刷新
//    - (void)p_addHeader
//    {
//        self.rightTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//
//            NSString *fileName = [NSString stringWithFormat:@"TJGZleft%ld.plist",self.presentIndexRow];
//            NSString *TJGZleftPath = [KESHAN stringByAppendingPathComponent:fileName];
//
//            if (self.leftArray.count == 0) return;
//
//
//            NSString *str = self.leftArray[self.presentIndexRow][@"id"];
//            NSString *urlStr = [NSString stringWithFormat:,str];
//
//            [WJNetTool GET:urlStr body:nil header:nil response:WJJSON success:^(id resuposeObject) {
//
//                NSDictionary *dic = resuposeObject;
//                NSArray *array = dic[@"list"];
//
//                //将数组写入本地
//                BOOL result = [NSKeyedArchiver archiveRootObject:array toFile:TJGZleftPath];
//                if (!result) {
//                    NSLog(@"推荐关注写入本地失败");
//                }
//                self.rightArray = [NSMutableArray array];
//                for (NSDictionary *dic in array) {
//                    WJRightModel *model = [[WJRightModel alloc]initWithDic:dic];
//                    [self.rightArray addObject:model];
//                    [model release];
//
//                }
//                [self.rightTableView reloadData];
//                [self.rightTableView.mj_header endRefreshing]; // 影藏小菊花
//
//
//            } failure:^(NSError *error) {
//
//                // 断网的时候加载本地数据
//                NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:TJGZleftPath];
//                self.rightArray = [NSMutableArray array];
//                for (NSDictionary *dic in array) {
//                    WJRightModel *model = [[WJRightModel alloc]initWithDic:dic];
//                    [self.rightArray addObject:model];
//                    [model release];
//
//                }
//                [self.rightTableView reloadData];
//                [self.rightTableView.mj_header endRefreshing]; // 影藏小菊花
//
//            }];
//
//        }];
//    }
//
//
//
//#pragma Mark - 上拉加载  还可以写另一个功能 就是快到底部的时候自动刷新出下一行
//    - (void)p_addFooter
//    {
//
//
//        self.rightTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//
//            NSString *fileName = [NSString stringWithFormat:@"TJGZleft%ld.plist",self.presentIndexRow];
//            NSString *TJGZleftPath = [KESHAN stringByAppendingPathComponent:fileName];
//
//            NSNumber *str = self.leftArray[self.presentIndexRow][@"id"];
//
//            // number已经不可以用来判断了
//            if ([self.number isEqual:str]) {
//                self.page = self.page + 1;
//
//            }else{
//                self.page = 1;
//                self.page = self.page + 1;
//                self.number = str;
//            }
//
//            NSString *urlStr = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=list&c=subscribe&category_id=%@&page=%ld",str,self.page];
//
//            [WJNetTool GET:urlStr body:nil header:nil response:WJJSON success:^(id resuposeObject) {
//
//                NSDictionary *dic = resuposeObject;
//                NSArray *array = dic[@"list"];
//
//                //将数组写入本地
//                BOOL result = [NSKeyedArchiver archiveRootObject:array toFile:TJGZleftPath];
//                if (!result) {
//                    NSLog(@"推荐关注写入本地失败");
//                }
//
//                // 上拉加载数组不可以为空
//                if (self.rightArray.count == 0 ) {
//                    return;
//                }
//
//                for (NSDictionary *dic in array) {
//                    WJRightModel *model = [[WJRightModel alloc]initWithDic:dic];
//                    [self.rightArray addObject:model];
//                    [model release];
//
//                }
//
//#pragma mark - 显示全部加载完毕  这里有问题 以后想明白了记录一下 endRefreshingWithNoMoreData 只执行一次结束了上啦刷新
//                [self.rightTableView reloadData];
//                [self.rightTableView.mj_footer endRefreshing];
//
//
//                //            NSLog(@"%ld",self.rightArray.count);
//                ////            NSString *name = self.leftArray[self.presentIndexRow][@"name"];
//                //            if ( self.rightArray.count == self.totol ) {
//                //
//                //                [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
//                //
//                //            }else{
//                //                [self.rightTableView.mj_footer endRefreshing];
//                //
//                ////                self.isName = name;
//
//                //            }
//
//
//            } failure:^(NSError *error) {
//
//                // 断网的时候加载本地数据
//                NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:TJGZleftPath];
//                self.rightArray = [NSMutableArray array];
//                for (NSDictionary *dic in array) {
//                    WJRightModel *model = [[WJRightModel alloc]initWithDic:dic];
//                    [self.rightArray addObject:model];
//                    [model release];
//
//                }
//                [self.rightTableView reloadData];
//                [self.rightTableView.mj_footer endRefreshing];
//
//            }];
//
//        }];
//
//
//    }
//





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
